package com.sw.study.scn.code.controller;

import com.sw.study.scn.code.service.CodeService;
import com.sw.study.scn.code.service.EmailServiceFeignClient;
import com.sw.study.scn.pojo.AuthCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/code")
public class CodeController {
    @Autowired
    private CodeService codeService;

    @Autowired
    private EmailServiceFeignClient emailServiceFeignClient;


    @Value("${server.port}")
    private Integer port;

    //⽣成验证码并发送到对应邮箱，成功
    //true，失败false
    @GetMapping("/create/{email}")
    public Boolean createEmail(@PathVariable String email) {
        //生成6位随机数字
        Double code = (Math.random()*9+1)*100000;
        String code1 = code.toString().substring(0,6);
        System.out.println(code1);
        codeService.codeSave(email,code1);
        emailServiceFeignClient.createEmail(email,code1);
        return true;
    }

    //校验超时
    @GetMapping("/validate/{email}/{code}")
    public Integer validateEmail(@PathVariable String email,@PathVariable String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        authCode = codeService.findOne(example);
        if(authCode==null){
            return 1;
        }else if(authCode.getExpiretime().before(new Date())){
            return 2;
        }else{
            return 0;
        }
    }
}
